package com.motion.service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.motion.dto.*;
import com.motion.generator.entity.*;
import com.motion.generator.mapper.*;
import com.tencentcloudapi.mps.v20190612.models.VideoTemplateInfo;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.math.BigInteger;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.util.*;
import java.util.stream.Collectors;

@Service
public class CourseService {
    @Autowired(required = false)
    private CourseClassMapper courseClassMapper;
    @Autowired(required = false)
    private CourseMapper courseMapper;
    @Autowired(required = false)
    private ActionMapper actionMapper;
    @Autowired(required = false)
    private UserMapper userMapper;
    @Autowired(required = false)
    private UserCourseMapper userCourseMapper;
    @Autowired(required = false)
    private CourseLinkMapper courseLinkMapper;

//    public void test(){
//        QueryWrapper<UserCourse> queryWrapper = new QueryWrapper<>();
//        queryWrapper.eq("userId", 2L);
//        userCourseMapper.selectOne(queryWrapper);
//    }
    //课程Abb封装
    public List<CourseAbb> CourseToAbb(List<Course> courseList){
        //临时变量
        List<CourseAbb> courseAbbList=new ArrayList<>();
        CourseAbb courseAbb=new CourseAbb();
        List<String> value=new ArrayList<>();
        for (Course course:courseList){
            //结构体类似指针的机制，每次必须开辟新空间，不然，项目添加到列表为没有改变
            courseAbb=new CourseAbb();
            BeanUtils.copyProperties(course,courseAbb);
            courseAbb.setBackgroundUrl(course.getBackgroundUrl());
            courseAbb.setCourseId(course.getCourseId());
            courseAbb.setCourseName(course.getCourseName());
            courseAbb.setOnline(course.getOnLine());
            //List<String> stringList=Arrays.asList(course.getLabels().split(";").clone());
            //lables查询

//            for (int t2=1;t2<stringList.size();t2++){
//                 value.add(courseClassMapper.selectById(Long.valueOf(stringList.get(t2))).getClassValue());
//            }
            courseAbb.setLabels(getCourseLabel(course.getCourseId()));
            courseAbbList.add(courseAbb);
        }
        return courseAbbList;
    }

    public IPage<Course> filterCourse(Long currentPage, Long pageSize, String bodyPart){
        QueryWrapper<Course> queryWrapper = new QueryWrapper<>();

        StringBuilder sql1;
        StringBuilder sql2;
        if (!bodyPart.isEmpty()){
            String[] bpt = classIdStr2classValue(bodyPart);

            sql1 = new StringBuilder("select courseId from Course where bodyPart like '%;");
            for (String part:bpt){
                sql1.append(part).append("%' or bodyPart like '%");
            }
            sql1 = new StringBuilder(sql1.substring(0, sql1.length() - 20));
            queryWrapper.inSql("courseId", sql1.toString());
        }
//        queryWrapper.inSql("courseId","select courseId from Course where bodyPart like '%4%'");
//        queryWrapper.inSql("courseId","select courseId from Course where degree like '%3%' or degree like '%2%'");
        return courseMapper.selectPage(new Page<>(currentPage, pageSize), queryWrapper);
    }

    public String[] classIdStr2classValue(String classIdStr) {
        QueryWrapper<CourseClass> queryWrapper_temp = new QueryWrapper<>();
        Long[] bpt_id = new Long[classIdStr.split(";").length];
        for (int i = 0; i < bpt_id.length; i++) {
            bpt_id[i] = Long.valueOf(classIdStr.split(";")[i]);
        }
        queryWrapper_temp.select("classValue").in("courseClassId", bpt_id);
        return courseClassMapper.selectObjs(queryWrapper_temp).toArray(new String[0]);
    }

    //2.人气课程
    public IPage<Course> hostCourse(Long page,Long size){
        QueryWrapper<Course> queryWrapper=new QueryWrapper<>();
        queryWrapper.orderByDesc("Hit");
        return courseMapper.selectPage(new Page<>(page,size),queryWrapper);
    }

    //2.1 List分类返回Course
    public IPage<Course> selectCourseByList(Long page, Long size, List<String> list){
        QueryWrapper<Course> queryWrapper=new QueryWrapper<>();
        for (int t=0;t<list.size();t++) {
            queryWrapper.like("Type",list.get(t)+";");
        }
        queryWrapper.orderByDesc("Hit");
        return courseMapper.selectPage(new Page<>(page,size),queryWrapper);
    }
    //2.2 String分类返回course
    public IPage<Course> selectCourseByStr(Long currentPage, Long pageSize, String bodyPart){
        return selectCourseByList(currentPage,pageSize, Arrays.asList(bodyPart.split(";").clone()));
    }


    //热门课程获取
    public List<CourseAbb> getHotCourse(Long page,Long size){
        QueryWrapper<Course> queryWrapper=new QueryWrapper<>();
        queryWrapper.orderByDesc("hits");
//        List<Course> courseList=courseMapper.selectList(queryWrapper);
        List<Course> courseList=courseMapper.selectPage(new Page<>(1, 10), queryWrapper).getRecords();
        return CourseToAbb(courseList);
    }

    //字符串变换Long列表
    public List<Long> StringToListLong(String str){
        List<Long> longList=new ArrayList<>();
        String[] stringList= str.split(";");
        String tem="";
        for (String item:stringList){
            if(!item.isEmpty()) {
                longList.add(Long.valueOf(item));
            }
        }
        return longList;
    }
    public List<Integer> StringToIntList(String str){
        List<Integer> longList=new ArrayList<>();
        String[] stringList= str.split(";");
        for (String item:stringList){
            if(!item.isEmpty()) {
                longList.add(Integer.valueOf(item));
            }
        }
        return longList;
    }
    //获取网页详细信息
//    public CourseActionDto getCourse(Long courseId,Long userId){
//
//        //结构体列表取特定列的列表
//        //设置actiondto
//        //迭代器
//        //设置i是否收藏
//    }

    //课程名模糊搜索
    public CourseAbbDto getCoursebyname(String coursename,Long page,Long size){
        QueryWrapper<Course> queryWrapper=new QueryWrapper<>();
        queryWrapper.like("courseName",coursename);

        //临时变量
        CourseAbbDto courseAbbDto=new CourseAbbDto();
        List<CourseAbb> courseAbbList=new ArrayList<>();
        List<Course> courseList=courseMapper.selectList(queryWrapper);
        IPage<Course> courseIPage=courseMapper.selectPage(new Page<Course>(page,size),queryWrapper);
        courseList=courseIPage.getRecords();
        courseAbbDto.setHasNext(courseIPage.isSearchCount());
        courseAbbDto.setCourseList(CourseToAbb(courseList));
        return courseAbbDto;
    }


    public Course getCourseById(Long courseId){
        return courseMapper.selectById(courseId);
    }

    public List<CourseClass> courseClassIdList2CourseClassList(List<Long> courseClassIdList){
        QueryWrapper<CourseClass> queryWrapper=new QueryWrapper<CourseClass>();
        queryWrapper.in("courseClassId", courseClassIdList);
        queryWrapper.select("classValue");
        return courseClassMapper.selectList(queryWrapper);
    }

    public List<ActionDto> actionIdListAndCountList2ActionDtoList(List<Long> actionIdList, List<Integer> countList){
        List<ActionDto> actionDtoList=new ArrayList<>();
        Iterator<Integer> longIterator = countList.iterator();
        List<Action> actionList=new ArrayList<>();
        for (Long item:actionIdList){
            Action tep=actionMapper.selectById(item);
            try{
                if(tep!=null){
                    actionList.add(tep);
                }
            }catch (Exception e) {
                e.printStackTrace();
            }
        }
        for (int t=0;t<actionList.size()-1;t++){
            Action item=actionList.get(t);
            ActionDto tem=new ActionDto();
            BeanUtils.copyProperties(item, tem);
            int count = longIterator.next();
            //每个action重复的次数，以及需要的时间
            tem.setCount(count);
            tem.setDuration((item.getDuration()*count));
            actionDtoList.add(tem);
        }
        //最后一个动作休息时间归零
        //未考虑actionList为0
        if(actionList.size()==0)
            return new ArrayList<>();
        Action item=actionList.get(actionList.size()-1);
        ActionDto tem=new ActionDto();
        item.setRestDuration(0);
        BeanUtils.copyProperties(item, tem);
        int count = longIterator.next();
        //每个action重复的次数，以及需要的时间
        tem.setCount(count);
        tem.setDuration((item.getDuration()*count));
        actionDtoList.add(tem);
        return actionDtoList;
    }
    public int ifUserCollectCourse(Long userId, Long courseId){
        QueryWrapper<UserCourse> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("userId",userId).eq("courseId",courseId);
        UserCourse userCourse = userCourseMapper.selectOne(queryWrapper);
        if (userCourse == null){
            return 0;
        }else{
            if(userCourse.getHasCollected()==1){
                if (userCourse.getHasBooked()==1){
                    return 11;
                }
                else{
                    return 10;
                }
            }else{
                if (userCourse.getHasBooked()==1){
                    return 1;
                }
                else{
                    return 0;
                }
            }
        }
    }
    public IPage<Course> keyword2CourseIPage(String str, Long page, Long size){
        QueryWrapper<Course> queryWrapper=new QueryWrapper<>();
        queryWrapper.like("courseName",str);
        return courseMapper.selectPage(new Page<Course>(page,size),queryWrapper);
    }
    //课程完成
    public int coursePlayCountAddOne(Long courseId, Long userId){
        try {
            QueryWrapper<UserCourse> queryWrapper=new QueryWrapper<>();
            queryWrapper.eq("courseId", courseId);
            queryWrapper.eq("userId",userId);
            UserCourse userCourse = userCourseMapper.selectOne(queryWrapper);
            int total = userCourse.getPlayCount()+1;
            userCourse.setPlayCount(total);
            userCourseMapper.updateById(userCourse);
            return total;
        } catch (Exception e){
            UserCourse userCourse = new UserCourse();
            userCourse.setUserId(userId);
            userCourse.setCourseId(courseId);
            userCourse.setPlayCount(1);
            userCourseMapper.insert(userCourse);
            e.printStackTrace();
            return 1;
        }
    }
    //解筛选id字符串
    public List<List<String>> CourseSelection2List(String bodyPart){
        List<String> list=Arrays.asList(bodyPart.split(";"));
        List<List<String>> classid=new ArrayList<>();
        List<CourseAbb> courseAbbList=new ArrayList<>();
        List<Course> courseList=new ArrayList<>();
        CourseAbbDto courseAbbDto=new CourseAbbDto();

        for (String item:list) {
            classid.add(Arrays.asList(item.split(",")));
        }
        return classid;
    }
    //sql查询语言拼接
    public String sqlStr(List<List<String>> classid) {
        StringBuilder sql1 = new StringBuilder("select courseId from Course where ");
        StringBuilder sql2 = new StringBuilder("( labels like '%;");//修改DoTo
        sql2.append(classid.get(0).get(0)).append(";%\'");
        for (int t2 = 1; t2 < classid.get(0).size(); t2++) {
            sql2.append(" or labels like '%;").append(classid.get(0).get(t2)).append(";%\'");
        }
        sql2.append(")");
        sql1.append(sql2);
        for (int t1 = 1; t1 < classid.size(); t1++) {
            sql2 = new StringBuilder(" and ( labels like '%;");
            sql2.append(classid.get(t1).get(0)).append(";%\'");
            for (int t2 = 1; t2 < classid.get(t1).size(); t2++) {
                sql2.append(" or labels like '%;").append(classid.get(t1).get(t2)).append(";%\'");
            }
            sql2.append(")");
            sql1.append(sql2);
        }
        return sql1.toString();
    }
//    public CourseAbbDto sqlStr2ourseAbbDto(String sql1,int isOnline,int isHot,Long page, Long size){
//        QueryWrapper<Course> queryWrapper=new QueryWrapper<>();
//        queryWrapper.inSql("courseId",sql1);
//        CourseAbbDto courseAbbDto=new CourseAbbDto();
//        //状态与排序判断
//        switch (isHot){
//            case 1:
//                queryWrapper.orderByDesc("hits");
//                break;
//            case 0:
//                queryWrapper.orderByDesc("createTime");
//                break;
//        }
//        switch (isOnline){
//            case 2:
//                queryWrapper.eq("onLine",1);
//                break;
//            case 3:
//                queryWrapper.eq("onLine",0);
//                break;
//        }
//        IPage<Course> courseIPage=courseMapper.selectPage(new Page<>(page,size),queryWrapper);
//        courseAbbDto.setHasNext(courseIPage.isSearchCount());
//        courseAbbDto.setCourseList(CourseToAbb(courseIPage.getRecords()));
//        return courseAbbDto;
//    }

    public List<Course> courseIdList2CourseList(List<Long> courseIdList){
        QueryWrapper<Course> queryWrapper = new QueryWrapper<>();
        queryWrapper.in("courseId", courseIdList);
        return courseMapper.selectList(queryWrapper);
    }

    public List<AdminCourseDto> CourseClassList2AdminCourseDtoList(List<Course> courseList){
        List<AdminCourseDto> adminCourseDtos=new ArrayList<>();
        AdminCourseDto adminCourseDto=new AdminCourseDto();
        for (Course item:courseList){
            adminCourseDto=new AdminCourseDto();
            adminCourseDto.setBackgroundUrl(item.getBackgroundUrl());
            adminCourseDto.setCounts(Arrays.asList(item.getActions().split(";")).size());
            adminCourseDto.setCourseId(item.getCourseId());
            adminCourseDto.setCourseName(item.getCourseName());
            adminCourseDto.setCreatetime(item.getCreateTime());
            adminCourseDto.setJoinNum(item.getCollections());
            adminCourseDto.setCreater(userMapper.selectById(item.getUploaderId()).getNickName());
            adminCourseDto.setOnLine(item.getOnLine());
            adminCourseDto.setActionCount(item.getCounts());
            //actio获取
            List<Action> actionList=new ArrayList<>();
            for (String tep:item.getActions().split(";"))
                actionList.add(actionMapper.selectById(Long.valueOf(tep)));
            adminCourseDto.setActions(actionList);
            adminCourseDto.setLabel(getLabel(item.getCourseId()));
            adminCourseDtos.add(adminCourseDto);
        }
        return adminCourseDtos;
    }

    public List<Long> getLabel(Long courseId){
        QueryWrapper<CourseLink> queryWrapper=new QueryWrapper<>();
        queryWrapper.eq("courseId",courseId);
        List<CourseLink> courseLinks=courseLinkMapper.selectList(queryWrapper);
        return courseLinks.stream().map(CourseLink::getCourseClassId).collect(Collectors.toList());
    }

    public IPage<Course> getPageAll(Long page,Long size){
        QueryWrapper<Course> queryWrapper=new QueryWrapper<>();
        queryWrapper.ne("courseId",0);
        return courseMapper.selectPage(new Page<Course>(page,size),queryWrapper);
    }

    public IPage<Course> getPageBystr(Long page, Long size, int ifonline, LocalDateTime starTime,LocalDateTime endTime,String searchStr){
        QueryWrapper<Course> queryWrapper=new QueryWrapper<>();
        queryWrapper.ne("courseId",0);
        if (ifonline!=2)
            queryWrapper.eq("onLine",ifonline);
        if(starTime!=null)
            queryWrapper.ge("createTime",starTime);
        if (endTime!=null)
            queryWrapper.le("createTime",endTime);
        if (!searchStr.equals(""))
            queryWrapper.like("courseName",searchStr);
        return courseMapper.selectPage(new Page<Course>(page,size),queryWrapper);
    }

    public List<String> getCourseLabel(Long courseId){
        QueryWrapper<CourseLink> queryWrapper=new QueryWrapper<>();
        queryWrapper.eq("courseId",courseId);
        List<CourseLink> courseLinks=courseLinkMapper.selectList(queryWrapper);
        List<String> stringList=new ArrayList<>();
        for (CourseLink item:courseLinks){
            stringList.add(courseClassMapper.selectById(item.getCourseClassId()).getClassValue());
        }
        return stringList;
    }

    //解筛选id字符串
    public List<List<Long>> CourseSelection2LongList(String bodyPart){
        List<String> list=Arrays.asList(bodyPart.split(";"));
        List<List<Long>> classid=new ArrayList<>();
        List<CourseAbb> courseAbbList=new ArrayList<>();
        List<Long> longList=new ArrayList<>();
        for (String item:list) {
            longList=new ArrayList<>();
            if (Arrays.asList(item.split(",")).size()==1 ) {
                //获取courseclass
                CourseClass courseclassAll=courseClassMapper.selectById(Long.valueOf(item));
                if(courseclassAll.getClassValue().equals("全部")) {
                    QueryWrapper<CourseClass> queryWrapper=new QueryWrapper();
                    queryWrapper.eq("ClassName",courseclassAll.getClassName());
                    queryWrapper.ne("CourseClassId",courseclassAll.getCourseClassId());
                    longList=courseClassMapper.selectList(queryWrapper).stream().map(CourseClass::getCourseClassId).collect(Collectors.toList());
                }else{
                    for (String item2 : Arrays.asList(item.split(","))) {
                        longList.add(Long.valueOf(item2));
                    }
                }
            }else{
                for (String item2 : Arrays.asList(item.split(","))) {
                    longList.add(Long.valueOf(item2));
                }
            }
            classid.add(longList);
        }
        return classid;
    }


    public CourseAbbDto List2courseAbbDto(Set<Long> longList, int isOnline, int isHot, Long page, Long size){
        QueryWrapper<Course> queryWrapper=new QueryWrapper<>();
        queryWrapper.in("courseId", longList);
        CourseAbbDto courseAbbDto = new CourseAbbDto();
        //状态与排序判断
        switch (isHot){
            case 1:
                queryWrapper.orderByDesc("hits");
                break;
            case 0:
                queryWrapper.orderByDesc("createTime");
                break;
        }
        switch (isOnline){
            case 2:
                queryWrapper.eq("onLine",1);
                break;
            case 3:
                queryWrapper.eq("onLine",0);
                break;
        }
        IPage<Course> courseIPage=courseMapper.selectPage(new Page<>(page, size), queryWrapper);
        courseAbbDto.setHasNext(courseIPage.isSearchCount());
        courseAbbDto.setCourseList(CourseToAbb(courseIPage.getRecords()));
        return courseAbbDto;
    }

    public List<Course> getCourseByLabels(List<Long> labelList){
//        List<Long> labelList = new ArrayList<>();
//        for(String str: labels.split(";")){
//            labelList.add(Long.valueOf(str));
//        }
        QueryWrapper<CourseLink> queryWrapper = new QueryWrapper<>();
        queryWrapper.in("courseClassId", labelList);
        queryWrapper.select("courseId");
        List<Long> result = new ArrayList<>();
        for(Object obj:courseLinkMapper.selectObjs(queryWrapper)){
            result.add(Long.valueOf(String.valueOf(obj)));
        }
        Set<Long> CourseIdList = new HashSet<>(result);

        QueryWrapper<Course> queryWrapper1 = new QueryWrapper<>();
        queryWrapper1.in("courseId", CourseIdList);
        queryWrapper1.orderByDesc("hits");
        return courseMapper.selectPage(new Page<>(1L, 10L), queryWrapper1).getRecords();
    }

    public Course insertCourse(Course course){
        courseMapper.insert(course);
        return course;
    }
    public boolean deleteCourse(Long courseId){
        courseMapper.deleteById(courseId);
        return true;
    }
    public Course updataCourse(Course course){
        courseMapper.updateById(course);
        return courseMapper.selectById(course);
    }

    public CourseAbbDto all2courseAbbDto(int isOnline, int isHot, Long page, Long size){
        QueryWrapper<Course> queryWrapper=new QueryWrapper<>();
        CourseAbbDto courseAbbDto = new CourseAbbDto();
        //状态与排序判断
        switch (isHot){
            case 1:
                queryWrapper.orderByDesc("hits");
                break;
            case 0:
                queryWrapper.orderByDesc("createTime");
                break;
        }
        switch (isOnline){
            case 1:
                queryWrapper.eq("onLine",1);
                break;
            case 0:
                queryWrapper.eq("onLine",0);
                break;
        }
        IPage<Course> courseIPage=courseMapper.selectPage(new Page<>(page, size), queryWrapper);
        courseAbbDto.setHasNext(courseIPage.isSearchCount());
        courseAbbDto.setCourseList(CourseToAbb(courseIPage.getRecords()));
        return courseAbbDto;
    }
    public List<Course> actionIdToCourse_imperfect(Long actionId){
        QueryWrapper<Course> queryWrapper=new QueryWrapper();
        queryWrapper.like("actions",String.valueOf(actionId));
        return courseMapper.selectList(queryWrapper);
    }
}

